#include "AppStateManager.hpp"
#include "../App.hpp"


AppStateManager::AppStateManager()
{

}

AppStateManager::~AppStateManager()
{
}

bool AppStateManager::IsEmpty()
{
	return m_stack.empty();
}

void AppStateManager::AddActiveState(AppState* statePtr)
{
	
   

	if(!m_stack.empty())
	{
		// Pause the current running state
		m_stack.back()->Pause();
	}

	// Add Active state
	m_stack.push_back(statePtr);

	// Initialize the active state
	statePtr->DoInit();

}

void AppStateManager::AddInactiveState(AppState* statePtr)
{
	// Add the inactive state on stack
	m_stack.insert(m_stack.begin(), statePtr);
}

AppState* AppStateManager::ActiveState()
{
	return m_stack.back();
}

void AppStateManager::InactivateActiveState()
{
	if(!m_stack.empty())
	{
		// Get Active State
		AppState* statePtr = m_stack.back();

		statePtr->Pause();

		m_stack.pop_back();

		m_stack.insert(m_stack.begin(), statePtr);

		statePtr = NULL;

	}

}

void AppStateManager::DropActiveState()
{
	if(!m_stack.empty())
	{
		//Get active state
		AppState* statePtr = m_stack.back();

		//Pause the currently active state
		statePtr->Pause();

		//De Init
		statePtr->DeInit();

		m_stack.pop_back();

		m_stack.insert(m_stack.begin(), statePtr);

		statePtr = NULL;
	}
}

void AppStateManager::ResetActiveState()
{
	if(!m_stack.empty())
	{
		// Get active state
		AppState* statePtr = m_stack.back();

		// Pause the currently active state
	    statePtr->Pause();

		// Reset
		statePtr->ReInit();

		// Resume
		statePtr->Resume();

		statePtr = NULL;
	}
}




void AppStateManager::RemoveActiveState()
{
	if(!m_stack.empty())
	{
		//Get the currently active state
		AppState* statePtr = m_stack.back();

		// Pause
		statePtr->Pause();

		// DeInit
		statePtr->DeInit();

		// Remove on stack
		m_stack.pop_back();

		statePtr = NULL;
	}

}

void AppStateManager::SetActiveState(const std::string nameID)
{
	std::vector<AppState*>::iterator iter;

	for(iter = m_stack.begin(); iter < m_stack.end(); iter++)
	{
		if((*iter)->NameID() == nameID)
		{
			AppState* statePtr = *iter;

			m_stack.erase(iter);

			if(!m_stack.empty())
			{
				m_stack.back()->Pause();
			}

			

			m_stack.push_back(statePtr);

			statePtr->Resume();

			statePtr = NULL;

		}
	}
}

bool AppStateManager::IsExistedState(const std::string nameID)
{
	std::vector<AppState*>::iterator iter;

	for(iter = m_stack.begin(); iter < m_stack.end(); iter++)
	{
		// if find a state with this nameID, return true
		if((*iter)->NameID() == nameID)
			return true;
	}

	// if no state exist with this nameID , return false
	return false;
}

void AppStateManager::HandleCleanUp()
{


}
